<?php

namespace app\xwam\model;

/**
 * Description of AppbaseModel
 *
 * @author SoChishun
 * @version 1.0 2017-2-23 zishusoft Added.
 */
class AppbaseModel extends \think\Model {

    // 不要检测字段
    protected $autoCheckFields = false;
    // 批量输入验证
    protected $patchValidate = true;

    /**
     * 返回数组消息
     * @param mixed $status 数据库执行结果
     * @param mixed $info 错误消息
     * @return array array('status'=>false, 'info'=>'消息') 或 array('status'=>false, 'info'=>$result)
     * @version 1.0 2015-3-26 SoChishun Added.
     * @version 2.0 2015-6-10 SoChishun base_return_array() 重命名为 returnMsg()
     * @version 2.1 2018-1-27 SoChishun returnMsg() 重命名为 infoMessage()
     */
    protected function infoMessage($status, $info = false) {
        if (FALSE === $status || is_null($status)) {
            $msg = array('status' => false, 'info' => ($info ? $info : $this->getError()));
        } else {
            // 如果status是id值则info=status,否则info=info
            $msg = array('status' => true, 'info' => (true === $status ? $info : $status));
        }
        return $msg;
    }

    /**
     * 分页
     * @param \Think\Page $page 分页组件
     * @param array $options 数据库查询配置,默认array('field' => '*', 'order' => 'id desc', 'group' => null, 'table' => null, 'cache' => 10);
     * @param array $paging_options 分页配置,默认array('page_size' => config('USER.PAGE_SIZE'), 'page_params' => null);
     * @return false|array
     * @version 1.0 2015-3-5> by sutroon
     * @version 1.1 2015-4-23 SoChishun $options新增TABLE选项,支持视图查询
     * @version 1.2 2015-4-24 SoChishun $options新增GROUPBY选项,支持联合查询;新增CACHE选项,支持缓存
     * @version 1.3 2015-10-26 SoChishun 新增Addon支持
     * @version 2.0 2015-11-13 SoChishun 重构
     * @version 2.1 2016-5-6 SoChishun 修改page_size参数
     * @version 2.2 2016-7-14 SoChishun 引用参数(&$pager)分页条字符串改为分页组件(&page), 新增pagesize变量
     * @version 2.3 2017-3-16 SoChishun 引用bootstrap3分页样式，get_paging_list()重命名为selectPaging()
     */
    public function selectPaging(\Think\Page &$page, $options = array(), $paging_options = array()) {
        $def_options = array('field' => '*', 'order' => 'id desc', 'table' => $this->tableName);
        $var_pagesize = config('VAR_PAGESIZE') ? config('VAR_PAGESIZE') : 'pagesize'; // 需设置Page.class.php ($this->nowPage = empty($_REQUEST[$this->p]) ? 1 : intval($_REQUEST[$this->p]);)
        $def_paging = array(
            'page_size' => (empty($_REQUEST[$var_pagesize]) ? config('LIST_ROWS') : intval($_REQUEST[$var_pagesize])), // 分页尺寸
            'page_params' => '', // 分页参数
        );
        $options = array_merge($def_options, $options);
        $paging_options = array_merge($def_paging, $paging_options);
        if (empty($paging_options['page_size'])) {
            $paging_options['page_size'] = 25;
        }
        $table = empty($options['table']) ? FALSE : $options['table'];
        if (empty($options['where'])) {
            $count = $table ? $this->table($table)->count() : $this->count();
        } else {
            $count = $table ? $this->table($table)->where($options['where'])->count() : $this->where($options['where'])->count();
        }
        // 2015-10-26 SoChishun 新增Addon支持
        if (defined('ADDON_NAME') && ADDON_NAME) {
            $paging_options['page_params']['addon'] = ADDON_NAME;
        }
        $page = new \Think\Page($count, $paging_options['page_size'], $paging_options['page_params']);
        //$page->setConfig('header', '<span class="rows">每页 ' . $paging_options['page_size'] . ' 条,共 %TOTAL_ROW% 条记录,页次: %NOW_PAGE%/%TOTAL_PAGE%</span>');
        //$page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        $page->setConfig('header', '每页' . $paging_options['page_size'] . '条 -- 共%TOTAL_ROW%条记录 -- %NOW_PAGE%/%TOTAL_PAGE%页次');
        $page->setConfig('theme', '<nav class="navbar"><div class="container-fluid"><div class="navbar-header"><ul class="pagination" style="margin:8px 0 0 0">%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%</ul></div><p class="navbar-text text-muted">%HEADER%</p></div></nav>');
        if ($page->listRows) {
            $options['limit'] = $page->firstRow . ',' . $page->listRows;
        }
        return $this->select($options);
    }

    /**
     * 当前分类以及所有子分类编号
     * <br />用于分类项目列表
     * @param integer $id 当前id
     * @return array
     * @version 1.0 2016-8-5 SoChishun Added.
     */
    public function base_getChildIds($id, $pid_key = 'pid', $id_key = 'id') {
        if (is_null($id)) {
            return false;
        }
        $aout = array($id);
        $ids = $this->where(array($pid_key => $id))->getField($id_key, true);
        if ($ids) {
            foreach ($ids as $id1) {
                $aout[] = $id1;
                $ids2 = $this->where(array($pid_key => $id1))->getField($id_key, true);
                if ($ids2) {
                    foreach ($ids2 as $id2) {
                        $aout[] = $id2;
                        $ids3 = $this->where(array($pid_key => $id2))->getField($id_key, true);
                        if ($ids3) {
                            foreach ($ids3 as $id3) {
                                $aout[] = $id3;
                            }
                        }
                    }
                }
            }
        }
        return $aout;
    }

    /**
     * 获取当前分类以及所有父分类列表
     * <br />用于分类项目列表页面的面包屑导航
     * @param int $id 当前编号
     * @param string $pid_key 父编号字段
     * @param string $field 字段列表
     * @return boolean
     * @version 1.0 2016-8-25 SoChishun Added.
     */
    function base_get_parent_list($id, $pid_key = 'pid', $field = 'id, title') {
        if (is_null($id)) {
            return false;
        }
        if (false === strpos($field, $pid_key)) {
            $field .= ', ' . $pid_key; // 必需包含$pid_key字段
        }
        $aout = array();
        $i = 4;
        while ($i > 0) {
            $adata = $this->field($field)->find($id);
            if ($adata) {
                $aout[$i] = $adata;
                if (empty($adata[$pid_key])) {
                    break;
                }
                $id = $adata[$pid_key];
            }
            $i--;
        }
        sort($aout);
        return $aout;
    }

    /**
     * 返回树形列表
     * @param array $selectOption array('table'=>'', 'field'=>'', 'where'=>array())
     * @param array $dataOption array('pid_field' => 'pid', 'id_key' => 'id', 'children_key' => 'children');
     * @return array
     * @throws \Exception
     * @version 1.0 2015-3-25 SoChishun Added.
     * @version 2.0 2015-10-22 SoChishun 重构,把参数整合成$select_options,$data-options
     * @version 2.1 2015-10-26 SoChishun 新增where条件数组限制,比较规范
     * @version 2.2 2016-7-25 SoChishun 重构，控制参数名称改小写,去掉first_where.
     * @version 2.3 2016-8-3 SoChishun 新增id_key选项
     * @version 2.4 2016-8-5 SoChishun 去掉pid默认值选项,改为硬编码值0
     * @version 2.5 2016-8-19 SoChishun 新增$child_where参数
     * @version 2.6 2017-3-17 base_select_tree_list()重命名为baseSelectTree()
     */
    public function baseSelectTree($selectOption = array(), $dataOption = array()) {
        if (!empty($selectOption['where']) && !is_array($selectOption['where'])) {
            throw new \Exception('[TREE]WHERE不是有效数组!');
        }
        $dataOption = array_merge(array('pid_field' => 'pid', 'id_key' => 'id', 'children_key' => 'children'), $dataOption);
        if (empty($selectOption['where'])) {
            $selectOption['where'] = array($dataOption['pid_field'] => 0);
        }
        $childWhere = array();
        if (isset($selectOption['child_where'])) {
            $childWhere = $selectOption['child_where'];
            unset($selectOption['child_where']);
        }
        return $this->baseSelectTreeFn($selectOption, $childWhere, $dataOption);
    }

    /**
     * 返回树形列表的子方法
     * @param type $selectOption
     * @param type $dataOption
     * @return type
     * @version 1.0 2015-3-25 SoChishun Added.
     * @version 1.1 2015-7-31 SoChishun 新增$children_key参数
     * @version 2.0 2015-10-22 SoChishun 重构,把参数整合成$select_options,$data-options
     * @version 2.1 2016-7-18 SoChishun 'chidren'空值由false改为array(),以匹配C#等强数据类型转换
     * @version 2.2 2016-7-25 SoChishun 重构，控制参数名称改小写.
     * @version 2.3 2016-8-5 SoChishun 修正array('id'=>$n)或pid=id时死循环的问题
     * @version 2.4 2016-8-19 SoChishun 新增$child_where参数
     * @version 2.5 2017-3-17 SoChishun base_get_tree_list_fn()重构为baseSelectTreeFn()
     */
    function baseSelectTreeFn($selectOption = array(), $childWhere = array(), $dataOption = array()) {
        $list =\think\Db::table($this->table)->fetchSql()->select($selectOption);
        export($list);
        exit;
        $aout = array();
        if ($list) {
            foreach ($list as $row) {
                $where = array($dataOption['pid_field'] => $row[$dataOption['id_key']]);
                if ($childWhere) {
                    $where = array_merge($childWhere, $where);
                }
                // 必需有子项目且pid不等于id
                if (\think\Db::table($this->table)->where($where)->count() > 0 && $row[$dataOption['pid_field']] != $row[$dataOption['id_key']]) {
                    $selectOption['where'] = $where;
                    $row[$dataOption['children_key']] = $this->baseSelectTreeFn($selectOption, $childWhere, $dataOption);
                } else {
                    $row[$dataOption['children_key']] = array();
                }
                $aout[] = $row;
            }
        }
        return $aout;
    }

    /**
     * 获取规范的Url参数sort
     * <br />如: $sortby = sofunc_get_orderby(I('sort'))
     * @param string $sort
     * @return boolean
     * @version 1.0 2015-2-2 by sutroon
     */
    function sofunc_get_orderby($sort) {
        if ($sort) {
            switch ($sort[0]) {
                case 'D':
                    return substr($sort, 1) . ' DESC';
                case 'A':
                    return substr($sort, 1);
                default:
                    return $sort;
            }
        }
        return false;
    }

}
